<template>
  <div class="user-details">
    <!-- 顶部背景区域 -->
    <div class="top-section">
      <div class="bg-overlay" :style="{ backgroundImage: `url(${userInfo.bkUrl || defaultCover})` }" :key="userInfo.bkUrl">
        <div class="bg-upload">
          <input type="file" @change="handleBackgroundChange" accept="image/*" />
          <i class="iconfont icon-camera"></i>
        </div>
      </div>
      
      <!-- 用户信息卡片 -->
      <div class="user-card">
        <div class="avatar-wrapper">
          <img :src="userInfo.avatarUrl || defaultAvatar" :key="userInfo.avatarUrl" alt="avatar" />
          <div class="avatar-upload">
            <input type="file" @change="handleAvatarChange" accept="image/*" />
            <i class="iconfont icon-edit"></i>
          </div>
        </div>
        <h2>{{ userInfo.username || '未设置昵称' }}</h2>
        <p class="user-account">{{ userInfo.account }}</p>
      </div>
    </div>

    <!-- 信息编辑区域 -->
    <div class="edit-section">
      <div class="edit-form">
        <div class="form-item">
          <input 
            v-model="userInfo.username" 
            type="text" 
            placeholder="昵称"
          >
          <i class="iconfont icon-user"></i>
        </div>

        <div class="form-item">
          <input 
            v-model="userInfo.email" 
            type="email" 
            placeholder="邮箱"
          >
          <i class="iconfont icon-email"></i>
        </div>

        <div class="form-item">
          <input 
            v-model="userInfo.password" 
            type="password" 
            placeholder="修改密码"
          >
          <i class="iconfont icon-lock"></i>
        </div>

        <div class="form-item textarea">
          <textarea 
            v-model="userInfo.description" 
            placeholder="介绍一下自己吧..."
            rows="4"
          ></textarea>
          <i class="iconfont icon-edit"></i>
        </div>
      </div>

      <button class="save-button" @click="saveProfile">
        保存修改
      </button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "UserDetails",
  data() {
    return {
      userInfo: {
        username: "",
        account: "",
        password: "",
        email: "",
        avatarUrl: "",
        bkUrl: "",
        description: ""
      },
      // defaultCover: require('@/assets/images/default-cover.jpg'),
      // defaultAvatar: require('@/assets/images/default-avatar.jpg'),
      baseUrl: 'http://etnor.xyz' // 添加基础URL
    };
  },
  methods: {
    async handleAvatarChange(event) {
      const file = event.target.files[0];
      if (file) {
        try {
          const formData = new FormData();
          formData.append('file', file);
          
          const response = await axios.post('/api/etnor/images/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          });
          
          if (response.data.url) {
            // 拼接完整的URL
            const fullUrl = this.baseUrl + response.data.url;
            this.$set(this.userInfo, 'avatarUrl', fullUrl);
            await this.saveProfile();
            this.$message.success('头像上传成功');
          }
        } catch (error) {
          this.$message.error('头像上传失败');
          console.error('头像上传失败:', error);
        }
      }
    },
    async handleBackgroundChange(event) {
      const file = event.target.files[0];
      if (file) {
        try {
          const formData = new FormData();
          formData.append('file', file);
          
          const response = await axios.post('/api/etnor/images/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          });
          
          if (response.data.url) {
            // 拼接完整的URL
            const fullUrl = this.baseUrl + response.data.url;
            this.$set(this.userInfo, 'bkUrl', fullUrl);
            await this.saveProfile();
            this.$message.success('背景图上传成功');
          }
        } catch (error) {
          this.$message.error('背景图上传失败');
          console.error('背景图上传失败:', error);
        }
      }
    },
    async saveProfile() {
      try {
        const response = await axios.post('/user/save', this.userInfo);
        if (response.data.code === 200) {
          await this.fetchUserInfo();
          return true;
        }
        return false;
      } catch (error) {
        this.$message.error('保存失败');
        console.error("保存失败:", error);
        return false;
      }
    },
    // 处理获取到的用户信息中的图片URL
    processUserInfo(info) {
      if (info.avatarUrl && !info.avatarUrl.startsWith('http')) {
        info.avatarUrl = this.baseUrl + info.avatarUrl;
      }
      if (info.bkUrl && !info.bkUrl.startsWith('http')) {
        info.bkUrl = this.baseUrl + info.bkUrl;
      }
      return info;
    },
    async fetchUserInfo() {
      try {
        const account = localStorage.getItem("account");
        const response = await axios.post('/user/details', { account });
        
        if (response.data.code === 200) {
          // 处理返回的用户信息中的图片URL
          this.userInfo = this.processUserInfo(response.data.data);
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
      }
    }
  },
  watch: {
    'userInfo.avatarUrl'(newVal) {
      console.log('头像更新为:', newVal);
    },
    'userInfo.bkUrl'(newVal) {
      console.log('背景图更新为:', newVal);
    }
  },
  mounted() {
    this.fetchUserInfo();
  }
};
</script>

<style scoped>
.user-details {
  min-height: 100vh;
  background: var(--bg-secondary);
  transition: all 0.3s ease;
}

.top-section {
  position: relative;
  height: 360px;
}

.bg-overlay {
  height: 260px;
  background-size: cover;
  background-position: center;
  position: relative;
  border-bottom: 1px solid var(--border-color);
}

.bg-upload {
  position: absolute;
  right: 20px;
  top: 20px;
  width: 36px;
  height: 36px;
  background: var(--card-bg);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  opacity: 0.9;
}

.bg-upload i {
  color: var(--text-primary);
}

.user-card {
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
  width: 90%;
  background: var(--card-bg);
  border-radius: 16px;
  padding: 20px;
  text-align: center;
  box-shadow: var(--card-shadow);
  border: 1px solid var(--border-color);
}

.avatar-wrapper {
  position: relative;
  width: 100px;
  height: 100px;
  margin: -70px auto 15px;
}

.avatar-wrapper img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 4px solid var(--card-bg);
  object-fit: cover;
}

.avatar-upload {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 32px;
  height: 32px;
  background: var(--primary-color);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.avatar-upload i {
  color: var(--text-light);
  font-size: 16px;
}

.user-card h2 {
  font-size: 20px;
  color: var(--text-primary);
  margin: 0;
}

.user-account {
  color: var(--text-secondary);
  font-size: 14px;
  margin: 5px 0 0;
}

.edit-section {
  padding: 20px;
}

.edit-form {
  background: var(--card-bg);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: var(--card-shadow);
  border: 1px solid var(--border-color);
}

.form-item {
  position: relative;
  margin-bottom: 16px;
}

.form-item input,
.form-item textarea {
  width: 100%;
  padding: 12px 40px 12px 16px;
  border: 1px solid var(--border-color);
  border-radius: 12px;
  font-size: 15px;
  background: var(--input-bg);
  color: var(--text-primary);
  transition: all 0.3s;
}

.form-item input::placeholder,
.form-item textarea::placeholder {
  color: var(--text-secondary);
}

.form-item input:focus,
.form-item textarea:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px var(--primary-shadow);
  outline: none;
}

.form-item i {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-secondary);
}

.form-item.textarea i {
  top: 20px;
  transform: none;
}

.form-item textarea {
  resize: none;
  padding: 16px;
}

.save-button {
  width: 100%;
  padding: 16px;
  background: var(--primary-color);
  color: var(--text-light);
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.save-button:hover {
  background: var(--primary-hover);
}

.save-button:active {
  transform: scale(0.98);
}

/* CSS变量，与父组件保持一致 */
:root {
  --primary-color: #007AFF;
  --primary-hover: #0056b3;
  --primary-shadow: rgba(0, 122, 255, 0.1);
  --text-light: #ffffff;
}

/* 适配深色模式 */
@media (prefers-color-scheme: dark) {
  :root {
    --bg-secondary: #121212;
    --card-bg: #1e1e1e;
    --input-bg: #2d2d2d;
    --text-primary: #e0e0e0;
    --text-secondary: #888;
    --border-color: #383838;
    --card-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  }
}

/* 适配浅色模式 */
@media (prefers-color-scheme: light) {
  :root {
    --bg-secondary: #f8f9fa;
    --card-bg: #ffffff;
    --input-bg: #ffffff;
    --text-primary: #333333;
    --text-secondary: #666666;
    --border-color: #eeeeee;
    --card-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  }
}
</style>
  